package com.zut.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zut.dto.DishDto;
import com.zut.mapper.DishMapper;
import com.zut.pojo.Dish;
import com.zut.pojo.DishFlavor;
import com.zut.service.DishFlavorService;
import com.zut.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;



    /*
    *
    *新增菜品到菜品表和口味表
    * */

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品信息到dish表
        super.save(dishDto);


        Long dishId = dishDto.getId(); //菜品id

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((flavor) ->{
            flavor.setDishId(dishId);
            return flavor;
        }).collect(Collectors.toList());


        //保存菜品口味到dish_flavor表
        dishFlavorService.saveBatch(flavors);

    }

    /*
    *
    *根据id查询菜品表和口味表
    *
    * */


    @Override
    public DishDto selectWithFlavor(Long id) {
        //根据id查询菜品表
        Dish dish = super.getById(id);

        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish,dishDto);

        //根据id查询口味表
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);

        return dishDto;
    }


    /*
    *
    *修改菜品和口味
    * */

    @Override
    public void updateWithFlavor(DishDto dishDto) {

        //更新菜品表
        super.updateById(dishDto);

        //更新口味表（删除后添加）——删除
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        //更新口味表（删除后添加）——添加
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((flavor) ->{
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }
}
